package gateway

import (
	"fmt"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/frame/g"
)

type ChuangLan struct {
	*Gateway
}

const (
	ENDPOINT_URL_TEMPLATE = "https://%s.253.com/msg/send/json"
	INT_URL = "http://intapi.253.com/send/json"
	CHANNEL_VALIDATE_CODE = "smsbj1"
	CHANNEL_PROMOTION_CODE = "smssh1"
)

func (s *ChuangLan) New(gateway *Gateway) (Channel, error) {
	return &ChuangLan{
		Gateway: gateway,
	}, nil
}

func (s *ChuangLan) Send() map[string]interface{} {
	IDDCode := s.To.GetIDDCode()
	if IDDCode == "" {
		IDDCode = "86"
	}
	params := g.Map{
		"account": g.Cfg().GetString("sms.gateways.chuanglan.account"),
		"password": g.Cfg().GetString("sms.gateways.chuanglan.password"),
		"phone": s.To.GetNumber(),
		"msg": s.WrapChannelContent(s.Message.GetContent(), IDDCode),
	}

	if IDDCode != "86" {
		params["mobile"] = IDDCode + s.To.GetNumber()
		if g.Cfg().GetString("sms.gateways.chuanglan.intel_account") != "" {
			params["account"] = g.Cfg().GetString("sms.gateways.chuanglan.intel_account")
		}
		if g.Cfg().GetString("sms.gateways.chuanglan.intel_password") != "" {
			params["password"] = g.Cfg().GetString("sms.gateways.chuanglan.intel_password")
		}
	}

	response := PostJson(s.BuildEndPoint(IDDCode), params, g.MapStrStr{})
	result := gconv.Map(response)
	if result["code"] != nil && gconv.Int(result["code"]) != 0 {
		panic(response)
	}

	return result
}

func (s *ChuangLan) BuildEndPoint(IDDCode string) string {
	channel := s.GetChannel(IDDCode)
	if INT_URL == channel {
		return channel
	}

	return fmt.Sprintf(ENDPOINT_URL_TEMPLATE, channel)
}

func (s *ChuangLan) GetChannel(IDDCode string) string {
	if IDDCode != "86" {
		return INT_URL
	}

	channel := CHANNEL_VALIDATE_CODE
	if g.Cfg().GetString("sms.gateways.chuanglan.channel") != "" {
		channel = g.Cfg().GetString("sms.gateways.chuanglan.channel")
	}

	if channel != CHANNEL_VALIDATE_CODE && channel != CHANNEL_PROMOTION_CODE {
		panic("Invalid channel for ChuanglanGateway.")
	}
	return channel
}

func (s *ChuangLan) WrapChannelContent(content, IDDCode string) string {
	channel := s.GetChannel(IDDCode)
	if CHANNEL_PROMOTION_CODE == channel {
		sign := g.Cfg().GetString("sms.gateways.chuanglan.sign")
		if sign == "" {
			panic("Invalid sign for ChuanglanGateway when using promotion channel")
		}
		unsubscribe := g.Cfg().GetString("sms.gateways.chuanglan.unsubscribe")
		if unsubscribe == "" {
			panic("Invalid unsubscribe for ChuanglanGateway when using promotion channel")
		}
		return sign + content + unsubscribe
	}
	return content
}